define(function (require, exports, module) {
    var angular = require('angular');
    require("pagination");
    require("angular-ui");
    require("/public/js/plugins/select2/select2");
    require('/public/js/myservice/contract/contract-common');
    var myMath = require('/public/js/myservice/common/my-math');
    var dialog = require("dialogplus");
    var util = require("util");
    var api_prefix = G_CONFIG["api_prefix"]; //api前缀
    var side = require('/public/js/myservice/side');
    var moment = require('moment');

    angular.module('ContractBase', ['select2', 'ngUI', 'ContractCommonService'])
        .filter('sumProductAmount', function () {
            return function (products) {
                var amount = 0;
                $.each(products, function (i, d) {
                    if (d.__type == 'delete') {
                        return;
                    }
                    amount = myMath.add(amount, d.authorization_type == 0 ? d.amount : 0);
                });
                return amount;
            };
        })
        .filter('countSMS', function () {
            return function (products) {
                var num = 0;
                $.each(products, function (i, d) {
                    if (d.__type == 'delete') {
                        return;
                    }
                    num = myMath.add(num, d.authorization_type == 1 ? d.authorization_numeric : 0);
                });
                return num;
            };
        })
        .filter('countProject', function () {
            return function (products) {
                var num = 0;
                $.each(products, function (i, d) {
                    if (d.__type == 'delete') {
                        return;
                    }
                    num = myMath.add(num, d.authorization_type == 0 ? d.authorization_numeric : 0);
                });
                return num;
            };
        })
        .controller('contractBaseCtrl', ['$scope', '$timeout', '$location', '$routeParams', 'contractCommonService', function ($scope, $timeout, $location, $routeParams, contractCommonService) {
            //合同基本信息
            $scope.contractBaseInfo = {
                customer_property: 0,
                contract_status: 0,
                is_cancelled: 0,
                give_work_day: 0,
                develop_work_day: 0,
                implement_work_day: 0
            };
            //产品列表
            $scope.projects = [];
            //先加载下拉框
            // 合同性质下拉框处理
            $scope.ddlConfigContractNature = {
                allowClear: false,
                data: [],
                placeholder: '合同性质',
                onchange2: function (selected) {
                    //获取公司下拉信息
                    contractCommonService.actionGetContractCompanyList(selected.id, function (data) {
                        var ddlData = [];
                        var isCompanyValid = false;
                        $.each(data, function (i, d) {
                            ddlData.push({id: d.company_id, text: d.company_name});
                            if (d.company_id == $scope.contractBaseInfo.company_id) {
                                isCompanyValid = true;
                            }
                        });
                        $scope.ddlConfigCompany.data = ddlData;
                        if (!isCompanyValid) {
                            //切换性质时清空签署公司
                            $scope.contractBaseInfo.company_id = null;
                        }

                        $scope.$applyAsync();
                    });
                }
            };

            //获取合同性质列表
            contractCommonService.getContractNatures(function (data) {
                var ddlData = [];
                $.each(data, function (i, d) {
                    ddlData.push({id: d.property_id, text: d.property_name});
                });
                $scope.ddlConfigContractNature.data = ddlData;
                $scope.$applyAsync();
            });

            // 合同签署公司下拉框处理
            $scope.ddlConfigCompany = {
                allowClear: false,
                data: [{id: 1, text: '明源云客'}],
                placeholder: '合同签署公司'
            };

            // 合同类别下拉框处理
            $scope.ddlConfigContractCategory = {
                allowClear: false,
                data: [{id: 1, text: '云客租用服务合同'}],
                placeholder: '合同类别'
            };

            //获取类别下拉信息
            contractCommonService.getContractCategories(function (data) {
                var ddlData = [];
                $.each(data, function (i, d) {
                    ddlData.push({id: d.category_id, text: d.category_name});
                });
                $scope.ddlConfigContractCategory.data = ddlData;
                $scope.$applyAsync();
            });


            // 合同小类下拉框处理
            $scope.ddlConfigContractSmallClass = {
                allowClear: false,
                data: [],
                placeholder: '合同小类'
            };

            // 合同大类下拉框处理
            $scope.ddlConfigContractBigClass = {
                allowClear: false,
                data: [],
                placeholder: '合同大类',
                onchange2: function (item) {
                    if (!item || !item.id) {
                        return;
                    }
                    contractCommonService.getContractSmallClass(item.id, function (data) {
                        var ddlData = [];
                        var curSmallClass = null;
                        $.each(data, function (i, d) {
                            ddlData.push({id: d.littler_category_id, text: d.littler_category_name});
                            if (d.littler_category_id == $scope.contractBaseInfo.littler_category_id) {
                                curSmallClass = {id: d.littler_category_id, text: d.littler_category_name};
                            }
                        });
                        $scope.ddlConfigContractSmallClass.data = ddlData;

                        $scope.$applyAsync();
                        setTimeout(function () {
                            $('#idSmallClass').length && $('#idSmallClass').data('select2').updateSelection(curSmallClass);
                        }, 0);

                    })
                }
            };

            //获取大类下拉信息
            contractCommonService.getContractBigClass(function (data) {
                var ddlData = [];
                $.each(data, function (i, d) {
                    ddlData.push({id: d.big_category_id, text: d.big_category_name});
                });
                $scope.ddlConfigContractBigClass.data = ddlData;
                $scope.$applyAsync();
            });

            // 合同签约地区下拉框处理
            $scope.ddlConfigContractSignArea = {
                allowClear: false,
                data: [{id: 1, text: '北京'}],
                placeholder: '合同签约地区'
            };
            //获取签约地区下拉信息
            contractCommonService.getContractAreas(function (data) {
                var ddlData = [];
                $.each(data, function (i, d) {
                    ddlData.push({id: d.regionId, text: d.regionName});
                });
                $scope.ddlConfigContractSignArea.data = ddlData;
                $scope.$applyAsync();
            });

            // 产品下拉框数据
            $scope.ddlConfigProjectsData = [];

            //获取产品下拉信息
            contractCommonService.getProducts(function (data) {
                var ddlData = [];
                $.each(data, function (i, d) {
                    ddlData.push($.extend({}, {id: d.application_id, text: d.application_name}, d));
                });
                $scope.ddlConfigProjectsData = ddlData;
            });

            //获取合同信息
            $scope.loadContract = function (contractId) {
                if (contractId) {
                    contractCommonService.getContract(contractId, function (data) {
                        setTimeout(function () {
                            $scope.contractBaseInfo = data.contract;
                            $scope.projects = data.application;
                            $('#idCustomerName').length && $('#idCustomerName').data('select2').updateSelection({text: data.contract.customer_name || ''});
                            $('#idSigner').length && $('#idSigner').data('select2').updateSelection({text: data.contract.sign_people_name || data.contract.sign_people_id});
                            $('#idCompanyId').length && $('#idCompanyId').data('select2').updateSelection({text: data.contract.company_name || ''});
                            var signDate = moment(data.contract.sign_date,'YYYY-MM-DD HH:mm:ss');
                            if(signDate.isValid()){
                                $scope.contractBaseInfo.sign_date = signDate.format('YYYY-MM-DD');
                            }
                            var inputDate = moment(data.contract.input_date,'YYYY-MM-DD HH:mm:ss');
                            if(inputDate.isValid()){
                                $scope.contractBaseInfo.input_date = inputDate.format('YYYY-MM-DD');
                            }
                            $scope.$applyAsync();
                        }, 500);

                    });
                }
            };

            var contractId = $routeParams.id;
            var fromContractId = $routeParams.pid;
            if (contractId) {
                //编辑模式先设为只读（复核状态），避免复核的合同先显示编辑按钮再隐藏导致的刷新
                $scope.contractBaseInfo.contract_status = 1;
                $scope.loadContract(contractId);
            } else if (fromContractId) {
                contractCommonService.getContract(fromContractId, function (data) {
                    setTimeout(function () {
                        $scope.contractBaseInfo = angular.extend(data.contract, {
                            contract_id: null,
                            contract_code: null,
                            input_date: null,
                            balance_status: 0,
                            is_violated: 0,
                            contract_status: 0,
                            is_cancelled: 0
                        });
                        if (data.application) {
                            $.each(data.application, function (i, d) {
                                d['__type'] = 'add';
                            })
                        }
                        $scope.projects = data.application;

                        $('#idCustomerName').length && $('#idCustomerName').data('select2').updateSelection({text: data.contract.customer_name || ''});
                        $('#idSigner').length && $('#idSigner').data('select2').updateSelection({text: data.contract.sign_people_name || data.contract.sign_people_id});
                        $('#idCompanyId').length && $('#idCompanyId').data('select2').updateSelection({text: data.contract.company_name || ''});
                        $scope.generalContractCode();
                        var signDate = moment(data.contract.sign_date,'YYYY-MM-DD HH:mm:ss');
                        if(signDate.isValid()){
                            $scope.contractBaseInfo.sign_date = signDate.format('YYYY-MM-DD');
                        }
                        var inputDate = moment(data.contract.input_date,'YYYY-MM-DD HH:mm:ss');
                        if(inputDate.isValid()){
                            $scope.contractBaseInfo.input_date = inputDate.format('YYYY-MM-DD');
                        }
                        $scope.$applyAsync();
                    }, 500);

                });
            }

            // 客户下拉框处理
            $scope.ddlConfigCustomer = {
                allowClear: false,
                placeholder: '客户简称',
                ajax: {
                    url: api_prefix + "erp-interface/get-erp-customer-info",
                    dataType: 'json',
                    delay: 250,
                    data: function (term) {
                        return {
                            keyword: term,
                            limit: 10
                        };
                    },
                    results: function (json, page) {
                        var data = [];
                        if (json.retCode === "0") {
                            data = json.data;
                            $.each(data, function (i, d) {
                                d.text = d.CstName;
                                d.id = d.CSTGUID;
                            });
                        }
                        return {results: data};
                    },
                    cache: true
                },
                escapeMarkup: function (markup) {
                    return markup;
                }, // let our custom formatter work
                minimumInputLength: 1,
                onchange2: function (newVal) {
                    $scope.contractBaseInfo.top_customer_name = newVal.DjCstName;
                    $scope.contractBaseInfo.customer_full_name = newVal.CstFullName;
                    $scope.contractBaseInfo.customer_name = newVal.CstName;
                    $scope.contractBaseInfo.customer_code = newVal.CstShortCode;
                },
                formatResult: formatCustomer,
                formatSelection: formatCustomerSelection // omitted for brevity, see the source of this page
            };
            function formatCustomer(repo) {
                if (repo.loading) return repo.text;

                return repo.text;
            }

            function formatCustomerSelection(repo) {
                return repo.text;
            }

            // 合同签约人下拉框处理
            $scope.ddlConfigContractSigner = {
                allowClear: false,
                ajax: {
                    url: api_prefix + "erp-interface/get-users",
                    dataType: 'json',
                    delay: 250,
                    data: function (term) {
                        return {
                            keyword: term,
                            limit: 10
                        };
                    },
                    results: function (json, page) {
                        var data = [];
                        if (json.retCode === "0") {
                            data = json.data;
                        }
                        return {results: data};
                    },
                    processResults: function (data, page) {
                        // parse the results into the format expected by Select2.
                        // since we are using custom formatting functions we do not need to
                        // alter the remote JSON data
                        return {
                            results: data.items
                        };
                    },
                    cache: true
                },
                escapeMarkup: function (markup) {
                    return markup;
                }, // let our custom formatter work
                minimumInputLength: 1,
                onchange2: function (newVal) {
                    $scope.contractBaseInfo.area_name = newVal.BUName;
                    $scope.contractBaseInfo.area_id = newVal.BUGUID;
                    $scope.contractBaseInfo.area_code = newVal.BUCode;
                },
                formatResult: formatRepo,
                formatSelection: formatRepoSelection // omitted for brevity, see the source of this page
            };

            function formatRepo(repo) {
                if (repo.loading) return repo.text;

                var markup = '<div class="clearfix" style="width: 300px;">' +
                    '<div class="clearfix">' +
                    '<div class="col-sm-6">' + repo.UserName + '</div>' +
                    '<div class="col-sm-18">' + repo.BUName + '</div>' +
                    '</div></div>';

                return markup;
            }

            function formatRepoSelection(repo) {
                return repo.text;
            }

            $scope.ddl2Customer = '';
            $scope.ddl2Type = '';
            $scope.ddl2Company = '';
            $scope.ddl2Category = '';
            $scope.ddl2BigClass = '';
            $scope.ddl2SmallClass = '';
            $scope.ddl2Signer = '';
            $scope.ddl2SignArea = '';
            $scope.ddl2Nature = '';

            function formatProduct(repo) {
                if (repo.loading) return repo.text;

                var markup = '<div class="clearfix">' +
                    '<div class="clearfix">' +
                    '<div class="col-sm-24">' + repo.application_name + '</div>' +
                    '</div></div>';

                return markup;
            }

            function formatProductSelection(repo) {
                return repo.application_name;
            }

            //新增/修改产品
            $scope.onProductEditShow = function ($data, $dialog, $dialogScope, oldProd) {
                $dialogScope.oldProd = oldProd;

                $dialogScope.$watch('data.authorization_numeric', function (itemVal) {
                    if ($dialogScope.data.authorization_type == 0) {
                        var period = $dialogScope.data.rent_period || 0;
                        $dialogScope.data.amount = Math.round(myMath.div(myMath.mul(myMath.mul(itemVal, period), $dialogScope.data.price), 12));
                    }
                });
                $dialogScope.$watch('data.rent_period', function (itemVal) {
                    if ($dialogScope.data.authorization_type == 0) {
                        var number = $dialogScope.data.authorization_numeric || 0;
                        $dialogScope.data.amount = Math.round(myMath.div(myMath.mul(myMath.mul(itemVal, number), $dialogScope.data.price), 12));
                    }
                });

                //免费短信金额为0，不允许修改
                $dialogScope.$watch('data.price', function(itemVal){
                    if(parseFloat(itemVal) == 0){
                        $dialogScope.data.amount = 0;
                    }
                })

                $dialogScope.ddlConfigProjects = {
                    allowClear: false,
                    data: $scope.ddlConfigProjectsData,
                    placeholder: '产品名称',
                    onchange2: function (item) {
                        $dialogScope.data.authorization_type = item.authorization_type;
                        $dialogScope.data.application_name = item.application_name;
                        $dialogScope.data.application_id = item.application_id;

                        if (item.authorization_type == 0 && item.applicationPrices.length) {
                            $dialogScope.data.price = item.applicationPrices[0].price;
                            var period = $dialogScope.data.rent_period || 0;
                            $dialogScope.data.amount = Math.round(myMath.div(myMath.mul(myMath.mul($dialogScope.data.authorization_numeric, period), $dialogScope.data.price), 12));
                        }

                        var appPrices = [];
                        $.each(item.applicationPrices || [], function (i, d) {
                            appPrices.push({id: d.price, text: d.unit});
                        });

                        $dialogScope.ddlConfigSMSPrice = {
                            allowClear: false,
                            data: appPrices,
                            placeholder: '标准单价',
                            onchange2: function (price) {
                                $dialogScope.data.unit = price.text;
                            }
                        };

                        $dialogScope.$applyAsync();

                    }
                };

            };
            $scope.addContractProduct = function ($data, $dialog, $dialogScope) {
                $scope.projects.push($.extend({__type: 'add'}, $data));
            };
            $scope.saveContractProduct = function ($data, $dialog, $dialogScope) {
                angular.extend($dialogScope.oldProd, $.extend({__type: 'update'}, $data));
            };

            $scope.delProject = function (proj) {
                /**
                 * 删除产品
                 */
                util.confirm('确定要删除此产品吗？', {
                    ok: function () {
                        angular.extend(proj, {__type: 'delete'});
                        $scope.$applyAsync();
                    }
                });

            };

            $scope.$watch('contractBaseInfo.sign_amount', function (newData) {
                if ($scope.contractBaseInfo.sign_amount != myMath.add($scope.contractBaseInfo.delivery_amount, $scope.contractBaseInfo.rent_amount)) {
                    $scope.contractBaseInfo.delivery_amount = myMath.sub($scope.contractBaseInfo.sign_amount, $scope.contractBaseInfo.rent_amount);
                }
            });
            $scope.$watch('contractBaseInfo.rent_amount', function (newData) {
                if ($scope.contractBaseInfo.sign_amount != myMath.add($scope.contractBaseInfo.delivery_amount, $scope.contractBaseInfo.rent_amount)) {
                    $scope.contractBaseInfo.delivery_amount = myMath.sub($scope.contractBaseInfo.sign_amount, $scope.contractBaseInfo.rent_amount);
                }
            });
            $scope.$watch('contractBaseInfo.delivery_amount', function (newData) {
                if ($scope.contractBaseInfo.sign_amount != myMath.add($scope.contractBaseInfo.delivery_amount, $scope.contractBaseInfo.rent_amount)) {
                    $scope.contractBaseInfo.rent_amount = myMath.sub($scope.contractBaseInfo.sign_amount, $scope.contractBaseInfo.delivery_amount);
                }
            });

            $scope.$watch('contractBaseInfo.customer_id', function (newVal) {
                $scope.generalContractCode();
            });
            $scope.$watch('contractBaseInfo.area_code', function (newVal) {
                $scope.generalContractCode();
            });

            $scope.generalContractCode = function () {
                if ($scope.contractBaseInfo.customer_code && $scope.contractBaseInfo.area_code) {
                    contractCommonService.genContractFlowCode($scope.contractBaseInfo.area_code, $scope.contractBaseInfo.customer_code,
                        $scope.contractBaseInfo.contract_code, function (data) {
                            $scope.contractBaseInfo.contract_code = data;
                            $scope.$applyAsync();
                        });
                }
            };

            $scope.save = function () {
                /**
                 * 保存
                 */
                var isNew = contractId ? false : true;
                //收集合同信息
                var baseInfo = $scope.contractBaseInfo;
                var projectsInfo = $scope.projects;

                var post_data = {
                    contract: baseInfo,
                    product: projectsInfo
                };
                var url;
                if (isNew) {
                    url = api_prefix + "/contract/add-contract";
                } else {
                    url = api_prefix + "/contract/update-contract";
                }

                util.myAjax({
                    url: url,
                    type: "POST",
                    context: this,
                    data: post_data,
                    success: function (json) {
                        if (json.retCode === "0") {
                            if (isNew) {
                                $location.path("base").search({id: json.data});
                                contractId = json.data;
                                setTimeout(function () {
                                    side.refresh();
                                }, 1000);
                                util.alert('合同创建成功', {
                                    ok: function () {
                                        setTimeout(function () {
                                            side.refresh();
                                        }, 500);
                                    }
                                });
                            } else {
                                util.alert("保存成功");
                            }

                            $scope.loadContract(contractId);

                        } else {
                            util.alert("保存失败：" + json.errMsg);
                        }
                    }
                });
            };

            $scope.verify = function () {
                /**
                 * 提交复核
                 */

            }
        }]);
});